(function () {

    $('#phone').on('dblclick','img',function(){
        $(this).remove();
    });

    $('#editor').on('dblclick','.line',function () {
        $(this).remove()
    });

   /*draw hr-line*/
    var createHrlineStatus = false;
    var createHrlineMouseStatus =false;
    $('.ruler-hr').on('mousedown',function () {
        createHrlineStatus =true;
        createHrlineMouseStatus = true
    });
    $('.ruler-hr').on('mouseup',function () {
        createHrlineStatus = false;
        createHrlineMouseStatus = false;

    });
    $('.ruler-hr').on('mouseleave','.ruler-hr',function (e) {
        createHrlineStatus = false;
    });
    $('#editor').on('mousemove','.ruler-hr',function (e) {
        if(createHrlineStatus){
            var div=document.createElement("div");
            createHrlineStatus = false
            div.setAttribute('class','line line-hr draggable');
            editor.appendChild(div)
        }
    });
    $('#editor').on('mousemove',function (e) {
       if(createHrlineMouseStatus){
        $('.line-hr').last().css('top',e.clientY)
       }
    });
    $('#editor').on('mouseup',function (e) {
        createHrlineMouseStatus = false;
    });
    $("div").prepend()
    /*draw vr-line*/
    var createVelineStatus = false;
    var createVelineMouseStatus =false;
    $('.ruler-ve').on('mousedown',function () {
        createVelineStatus =true;
        createVelineMouseStatus = true;
    });
    $('.ruler-ve').on('mouseup',function () {
        createVelineStatus = false;
        createVelineMouseStatus = false;

    });
    $('.ruler-ve').on('mouseleave','.ruler-ve',function (e) {
        createVelineStatus = false;
    });
    $('#editor').on('mousemove','.ruler-ve',function (e) {
        if(createVelineStatus){
            var div=document.createElement("div");
            createVelineStatus = false;
            div.setAttribute('class','line line-ve draggable');//draggable
            editor.appendChild(div)
        }
    });
    $('#editor').on('mouseup','.line-ve',function (e) {

        $(this).attr('data-x',e.pageX-DIV_Left)
    });


    var DIV_Left;
    $('#editor').on('mousemove',function (e) {

        if(createVelineMouseStatus){
            DIV_Left=$(".am-u-sm-9").offset().left;
            // console.log(e.pageX)
            $('.line-ve').last().css('left',e.pageX-DIV_Left);
            // createVelineMouseStatus=false;
        }
    });
    console.log($(".am-u-sm-9").offset().left)
    $('#editor').on('mouseup',function (e) {
        createVelineMouseStatus = false;
    });

    imgbg.onchange=function (e) {
        const file ='images/' +e.srcElement.files[0].name;
        $('#phone').css('background-image','url('+file+')')
        $('.swiper-slide').css('background-image','url('+file+')')
    };
    createHtml.onclick=function(){

        document.querySelector('.swiper-slide').innerHTML = phone.innerHTML;
        $('.swiper-slide img').removeAttr('style data-x data-y');
        $('.swiper-slide img').removeClass('draggable');
        $("#phone").find('img').removeClass('act');
        $('#textarea').text(document.querySelector('.swiper-slide').outerHTML.toString().replace(/&quot;/g,'\''));

        $('#my-alert').modal();
        $("#textarea").focus();
        $("#textarea").select();

    };
    clearHtml.onclick = function () {
        swal({
            title: '你确定重做么?',
            text: "执行只操作后文件不可恢复",
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            cancelButtonText: '取消',
            confirmButtonText: '我要重做'
        }).then((result) => {
            if (result.value) {
                swal(
                    '重做成功',
                    '页面内容已经清空',
                    'success'
                )

                phone.innerHTML = '';
                $('#phone').css('background-image','')
            }
        })
    }

    preview.onclick=function () {
      $('#phone img').hide();
      $('#phone img').each(function () {
          $(this).velocity($(this).attr('animate') || 'transition.bounceUpIn' ,{duration:$(this).attr('duration') || 750,delay:$(this).attr('delay') || 500});

      })
    };
    /*H5尺寸切换*/
    var H5_psd_width=640;
    $("input[name='applicationSystem']").on('click',function () {
        var type = $(this).val();
        if (type == '1'){
            $('#phone').css({
                width:640,
                height:1040
            });
            H5_psd_width=640
        }else {
            $('#phone').css({
                width:750,
                height:1220
            });
            H5_psd_width=750
        };
    });
    /*H5 element options*/
    var options={
        class:['image','animate']
    };
    $("input[name='animate']").on('click',function () {
        var type = $(this).val();
        if (type == '1'){
            options={
                class:['image','animate']
            };
        }else {
            options={
                class:['ani','image'],
                attr:['swiper-animate-effect','swiper-animate-duration','swiper-animate-delay']
            };
        };
    });

// target elements with the "draggable" class
    interact('.draggable')
        .draggable({
            // enable inertial throwing
            inertia: true,
            // keep the element within the area of it's parent
            restrict: {
                restriction: "parent",
                endOnly: true,
                elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
            },
            // enable autoScroll
            autoScroll: true,

            // call this function on every dragmove event
            onmove: dragMoveListener,
            // call this function on every dragend event
            onend: function (event) {
                var textEl = event.target.querySelector('p');

                textEl && (textEl.textContent =
                    'moved a distance of '
                    + (Math.sqrt(Math.pow(event.pageX - event.x0, 2) +
                    Math.pow(event.pageY - event.y0, 2) | 0))
                        .toFixed(2) + 'px');
            }
        });

    function dragMoveListener (event) {
        var target = event.target,

            // keep the dragged position in the data-x/data-y attributes
            x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
            y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

        // translate the element
        target.style.left = x + 'px';
        target.style.top = y + 'px';

        // update the posiion attributes
        if(event.target.tagName !== 'DIV'){
            var l= (x/H5_psd_width*10).toFixed(2);
            var t= (y/H5_psd_width*10).toFixed(2);
            //setAttribute("class","test1");
            target.setAttribute('class',options.class[0]+' '+options.class[1]+' '+'draggable');
            if(options.attr){
                target.setAttribute(options.attr[0],'');
                target.setAttribute(options.attr[1],'0.5s');
                target.setAttribute(options.attr[2],'0.5s');
            }

            target.setAttribute('lt', l+'/'+t);
        }

        target.setAttribute('data-x', x);
        target.setAttribute('data-y', y);
    }

// this is used later in the resizing and gesture demos
    window.dragMoveListener = dragMoveListener;

    /*file upload*/
    imgread.addEventListener("change",selectimage , false);


    phone.addEventListener("dragenter", ingroeDrop, false);
    phone.addEventListener("dragover", ingroeDrop, false);
    phone.addEventListener("drop", drop, false);

    function ingroeDrop(e) {
        e.stopPropagation();
        e.preventDefault();
    }

    function drop(e) {
        e.stopPropagation();
        e.preventDefault();

        var dt = e.dataTransfer;
        var files = dt.files;

        handleFiles(files);
    }

    function selectimage() {

        handleFiles(this.files);
    }


    /*处理文件*/
    function handleFiles(files) {
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            if (!file.type.startsWith('image/')){ continue }
            var img = document.createElement("img");
            img.classList.add("draggable");
            img.src = 'images/'+file.name;
            phone.appendChild(img);
        }
    }











   //点击拖动的图片添加class，并给图片设置动画选项，右侧按钮
   $("#phone").on('click','img',function () {
       $("#phone").find("img").removeClass('act');
       $(this).addClass('act');
       $('.js--triggerAnimation').attr("disabled",false);
   });
    $("#phone").on('mousedown','img',function () {
        $("#phone").find("img").removeClass('act');
        $(this).addClass('act');
        $('.js--triggerAnimation').attr("disabled",false);
    });
    $("#phone").on('mouseup','img',function () {
        $("#phone").find("img").removeClass('act');
        $(this).addClass('act');
        $('.js--triggerAnimation').attr("disabled",false);
    });
    $('.js--triggerAnimation').on('click',function () {
        var animations=$('.js--animations').val()
        console.log($('.js--animations').val());
        $("#phone").find('.act').addClass("animated");
        $("#phone").find('.act').addClass(animations);

        $("#phone").find('.act').attr('swiper-animate-effect',animations);
        var timer=setTimeout(function () {
            $("#phone").find('.act').removeClass(animations);
            $("#phone").find('.act').removeClass("animated");
            clearTimeout(timer)
        },800)
    });
    $('#l-middle').on('click',function () {
        // alert(1);
        $("#phone").find(".act").addClass("Center")
    });


/*select2*/
    /*常用选项配置*/
    var arrDefault=["callout.bounce", "callout.shake", "callout.flash", "callout.pulse", "callout.swing", "callout.tada", "transition.fadeIn", "transition.fadeOut", "transition.flipXIn", "transition.flipXOut", "transition.flipYIn", "transition.flipYOut", "transition.flipBounceXIn", "transition.flipBounceXOut", "transition.flipBounceYIn", "transition.flipBounceYOut", "transition.swoopIn", "transition.swoopOut", "transition.whirlIn", "transition.whirlOut", "transition.shrinkIn", "transition.shrinkOut", "transition.expandIn", "transition.expandOut", "transition.bounceIn", "transition.bounceOut", "transition.bounceUpIn", "transition.bounceUpOut", "transition.bounceDownIn", "transition.bounceDownOut", "transition.bounceLeftIn", "transition.bounceLeftOut", "transition.bounceRightIn", "transition.bounceRightOut", "transition.slideUpIn", "transition.slideUpOut", "transition.slideDownIn", "transition.slideDownOut", "transition.slideLeftIn", "transition.slideLeftOut", "transition.slideRightIn", "transition.slideRightOut", "transition.slideUpBigIn", "transition.slideUpBigOut", "transition.slideDownBigIn", "transition.slideDownBigOut", "transition.slideLeftBigIn", "transition.slideLeftBigOut", "transition.slideRightBigIn", "transition.slideRightBigOut", "transition.perspectiveUpIn", "transition.perspectiveUpOut", "transition.perspectiveDownIn", "transition.perspectiveDownOut", "transition.perspectiveLeftIn", "transition.perspectiveLeftOut", "transition.perspectiveRightIn", "transition.perspectiveRightOut"]
    arrDefault.forEach(function (item) {

        $('#default_select_option').append($('<option>'+item +'</option>'))
    })
    var arrMy=["self_transition.scaleIn","self_transition.scaleSmallIn","self_transition.scaleSmallBigIn","self_transition.scaleFadeOut","self_transition.slideRightOut", "self_transition.perspectiveDownOut","self_transition.perspectiveLeftUpIn","self_transition.perspectiveLeftUpOut","self_transition.perspectiveLeftDownIn","self_transition.perspectiveLeftDownOut","self_transition.perspectiveRightDownOut","self_transition.scrollScaleIn","self_transition.scrollBigIn","self_transition.slideLeftOut", "self_transition.slideUpOut","self_transition.slideLeftIn","self_transition.fadeIn","self_transition.slideDownIn","self_transition.slideRightIn","self_transition.slideRightScaleIn","self_transition.slideLeftDownIn","self_transition.slideLeftUpIn","self_transition.slideRightDownIn", "self_transition.slideRightUpIn","self_transition.rotateLeftUpIn","self_transition.rotateRightDownIn","self_transition.rotateLeftUpOut", "self_transition.slideUpIn","self_transition.slideDownOut","self_transition.scaleRotateIn","self_transition.scaleRotateOut", "self_transition.scaleOut","self_transition.pulseIn","self_transition.slideUpScaleIn", "self_transition.slideUpScaleOut","self_transition.slideDownScaleIn", "self_transition.slideDownScaleOut","self_transition.ScaleBigOut","self_transition.textIn","self_transition.meteorFirstIn","self_transition.meteorSecondIn","self_transition.meteorThirdIn","self_transition.meteorThirdIn","self_transition.translateXIn","self_transition.translateXIn","self_transition.perspectiveLeftIn","self_transition.perspectiveLeftOut","self_transition.perspectiveRightIn","self_transition.perspectiveRightOut","self_transition.perspectiveUpIn", "self_transition.perspectiveUpOut","self_transition.perspectiveDownIn","self_transition.perspectiveDownOut","self_transition.flipBounceXIn","self_transition.flipBounceXOut","self_transition.flyLeafIn", "self_transition.flyLeafOut","self_transition.DropIn","self_transition.DropOut","self_transition.jumpIn","self_transition.jumpOut","self_transition.DropThreeIn","self_transition.DropThreeOut","self_transition.swoopLeftIn","self_transition.swoopLeftOut","self_transition.swoopRightIn","self_transition.swoopRightOut", "self_transition.swoopUpIn","self_transition.swoopUpOut", "self_transition.swoopDownIn", "self_transition.swoopDownOut", "self_transition.whirlIn","self_transition.whirlOut","self_transition.bounceIn","self_transition.bounceOut","self_transition.scrollScaleOut","self_transition.scaleTreeIn","self_transition.slideLeftThreeOut"]
    arrMy.forEach(function (item) {
        $('#my_select_option').append($('<option>'+item +'</option>'))
    })
    function matchStart(params, data) {
        // If there are no search terms, return all of the data
        if ($.trim(params.term) === '') {
            return data;
        }

        // Skip if there is no 'children' property
        if (typeof data.children === 'undefined') {
            return null;
        }

        // `data.children` contains the actual options that we are matching against
        var filteredChildren = [];
        $.each(data.children, function (idx, child) {
            if (child.text.toUpperCase().indexOf(params.term.toUpperCase()) >= 0) {
                filteredChildren.push(child);
            }
        });

        // If we matched any of the timezone group's children, then set the matched children on the group
        // and return the group object
        if (filteredChildren.length) {
            var modifiedData = $.extend({}, data, true);
            modifiedData.children = filteredChildren;

            // You can return modified objects from here
            // This includes matching the `children` how you want in nested data sets
            return modifiedData;
        }

        // Return `null` if the term should not be displayed
        return null;
    }

    $(".js-example-basic-single").select2({
        matcher:matchStart
    });

   // data-animate='{"name":"transition.bounceIn","time":"550","delay":"500"}'
    $('.js-example-basic-single').on('change',function () {
        console.log($(this).val());


        $('.act').attr('animate',$(this).val());
        $('.act').velocity($('.act').attr('animate') || 'transition.bounceUpIn' ,{duration:$('.act').attr('duration') || 750,delay:$('.act').attr('delay') || 500});

    })

    /*配置动画时间*/
    $('#duration').on('blur',function () {

        $('.act').attr('duration',$(this).val());
        $('.act').velocity($('.act').attr('animate') || 'transition.bounceUpIn' ,{duration:$('.act').attr('duration') || 750,delay:$('.act').attr('delay') || 500});

    })
    /*配置动画延迟*/
    $('#delay').on('blur',function () {
        $('.act').attr('delay',$(this).val());
        $('.act').velocity($('.act').attr('animate') || 'transition.bounceUpIn' ,{duration:$('.act').attr('duration') || 750,delay:$('.act').attr('delay') || 500});

    })
})();